package com.example.billw.controller;

import com.example.billw.entity.Users;
import com.example.billw.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/")
    public String toLogin(){
        return "main/login";
    }
    /*@GetMapping("/login")
    public String toLoginPage(){
        return "main/login";
    }*/

    @PostMapping("/login")
    public String login(String username, String password, HttpServletRequest request){
        System.out.println(username);
        System.out.println(password);
        List<Users> users = userMapper.getUsers(new Users(username, 0));
        if (users.size() > 0){
            Users user = users.get(0);
            if (password.equals(user.getPassword())) {
                request.getSession().setAttribute("loginUser", user);
            }
        }
        return "redirect:home";
    }
    @RequestMapping("/home")
    public String toHome() {
        return "main/home";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("loginUser");
        return "redirect:login";
    }
}
